<?php
namespace app\services;

class RedisCacheService extends BaseService {
    private $redis = null;
    
    public function init() {
        $this->redis = \Yii::$app->redis;
        if (!$this->redis->ping()) {
            return [];
        }
    }

    public function cacheSolutionDailyBudget($solutionId = '') {
        $serv = new SolutionService();
        $sql = "select id, budget, budget_flag from {{%solution}}";
        if ($solutionId) $sql .= " where id = $solutionId";
        $solutions = $this->query($sql);
        foreach ($solutions as &$solution) {
            $solution['daily_budget'] = 0;
            if ($solution['budget']) {
                $solution['daily_budget'] = $solution['budget'];
            }
            if ($solution['budget_flag'] == 1) {
                $solution['daily_budget'] = $serv->getSolutionDailyBudget($solution['id']);
            }
        }

        foreach ($solutions as $solu) {
            list($id, $budget, $budget_flag, $daily_budget) = array_values($solu);
            $this->redis->hmset('solution:'.$id, 'daily_budget', $daily_budget);
        }
    }

    public function getCacheSolutionBudget($solutionId) {
        $cache = $this->redis->hget('solution:'.$solutionId, 'daily_budget');
        if(!$cache) $cache = 0;
        return $cache;
    }
}//end
